<template>
  <div class="publish-content">
    <baseTable
      :page.sync="page"
      :cols="tableCols"
      :data="tableData"
      :hasCheck="true"
      @select-change="handleSelectionChange"
    >
      <template #head>
        <div class="head">
          <div class="search">
            <el-cascader
              v-model="areaInfo"
              :options="cityList"
              :props="casxaderProps"
              placeholder="区县"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
            ></el-cascader>
            <el-input
              placeholder="请输入入统项目名称、所属项目名称"
              v-model="params.projectName"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search cursor-pointer"
                @click="getList"
              ></i>
            </el-input>
          </div>
          <div>
            <download
              type="complete-list"
              :params="listDownloadParams"
              :dataCheck="handleListDownload"
              :permission="PERMISSIONS.入统台账列表下载"
            />
            <download
              type="complete-detail"
              :params="detailDownloadParams"
              :dataCheck="handleDetailDownload"
              :permission="PERMISSIONS.入统台账详情下载"
            />
          </div>
        </div>
      </template>
      <template #cols>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              slot="reference"
              class="mr-10"
              @click="handleDetailClick(scope.row)"
            >
              {{ scope.row.test || '详情' }}
            </el-button>
          </template>
        </el-table-column>
      </template>
    </baseTable>
  </div>
</template>

<script>
import baseTable from '@c/base-table'
import { queryQuotaList, releaseIndex } from '@/api/indicator-manage'
import { queryArea } from '@api/question'
import { changeSubmitStatus, exportExcel, querySubmit } from '@api/city-index'
import { Message } from 'element-ui'
import axios from 'axios'
import { PERMISSIONS } from '@/common/user'
import { mapGetters } from 'vuex'
import { getProjectLedgerCompleteQuery } from '@/api/project-update/project-ledger'
import Download from '@/views/project-update/components/download.vue'
export default {
  name: 'dataRelaes',
  components: { Download, baseTable },
  computed: {
    ...mapGetters(['currentUser', 'user']),
  },
  data() {
    return {
      PERMISSIONS,
      wordPreviewVisible: false,
      pkName: '',
      tempBlob: null,
      page: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      params: {
        regionId: null,
        projectName: null,
      },
      tableData: [],
      tableCols: [
        {
          prop: 'regionName',
          label: '区县',
        },
        {
          prop: 'projectName',
          label: '入统项目名称',
        },
        {
          label: '所属项目名称',
          prop: 'belongProjectName',
        },
        {
          label: '入统行业代码',
          prop: 'projectNo',
        },
        {
          label: '累计入统金额（亿元）',
          prop: 'totalInvestment',
        },
        {
          label: '年初截至本月入统金额（亿元）',
          prop: 'addInvestment',
        },
      ],
      cityList: [],
      casxaderProps: {
        value: 'areaCode',
        label: 'areaName',
        // checkStrictly: true,
        children: 'children',
      },
      areaInfo: [],
      yearOptions: [
        {
          value: '2021',
          label: '2021年',
        },
        {
          value: '2022',
          label: '2022年',
        },
        {
          value: '2023',
          label: '2023年',
        },
        {
          value: '2024',
          label: '2024年',
        },
      ],
      listDownloadParams: {
        regionId: '',
        projectName: '',
      },
      detailDownloadParams: {},
      statusList: [
        { label: '待提交', value: 0 },
        { label: '待审核', value: 2 },
        { label: '已通过', value: -1 },
        { label: '退回', value: 1 },
        { label: '未填写', value: -2 },
      ],
      multipleSelection: [],
    }
  },
  mounted() {
    this.getList()
    queryArea({
      districtFlag: 'true',
    }).then((res) => {
      if (res.success) {
        const node = this.findNodeById(res.data, this.user.refId)
        this.cityList = this.removeChildrenAtLevel([node], 1)[0].children
      }
    })
  },
  methods: {
    handleListDownload() {
      return new Promise((resolve, reject) => {
        // if (this.multipleSelection.length) {
        // } else {
        this.listDownloadParams = {
          regionId: this.params.regionId,
          projectName: this.params.projectName,
        }
        resolve()
        // }
      })
    },
    handleDetailDownload() {
      return new Promise((resolve, reject) => {
        if (this.multipleSelection.length) {
          this.detailDownloadParams = this.multipleSelection.map((item) => {
            const { regionId, projectId, projectName } = item
            return {
              regionId,
              projectId,
              projectName,
            }
          })
          resolve()
        } else {
          // this.detailDownloadParams = {
          //   pkid: this.tableData.map((item) => item.pkid).join(','),
          // }
          // this.$message.warning('请选择要下载的数据')
          this.detailDownloadParams = []
          // reject()
          resolve()
        }
      })
    },
    handleDetailClick(row) {
      this.$router.push({
        path: '/project-update/unified-ledger-detail',
        query: {
          regionId: row.regionId,
          projectId: row.projectId,
          projectName: row.projectName,
        },
      })
    },
    findNodeById(tree, targetId) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的ID是否为目标ID
        if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
          // 如果是的话，返回当前节点
          return tree[i]
        }

        // 如果当前节点有子节点，则递归在子节点中查找
        if (tree[i].children && tree[i].children.length > 0) {
          const foundNode = this.findNodeById(tree[i].children, targetId)
          // 如果在子节点中找到了，则返回找到的节点
          if (foundNode !== undefined) {
            return foundNode
          }
        }
      }

      // 如果在树中没有找到目标ID，则返回undefined
      return undefined
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleChangeArea(val) {
      this.page.pageIndex = 1
      this.params.regionId = val[val.length - 1]
    },
    getList() {
      getProjectLedgerCompleteQuery({ ...this.page, ...this.params }).then(
        (res) => {
          if (res.success) {
            this.tableData = res.data.list
            this.page.total = res.data.count
          } else {
            this.$message.error(res.message)
          }
        }
      )
      // this.tableData = [
      //   {
      //     status: '未提交',
      //     regionName: '九龙坡区',
      //     taskName: '九龙坡区更新项目',
      //     batch: '2024年入库',
      //     projectType: '老旧街区',
      //     projectStage: '储备阶段',
      //     createTime: '2024-10-12 13:45:16',
      //     completeTime: '2024-10-18 09:14:43',
      //   },
      // ]
      // this.page.total = 1
    },
    getData() {
      queryQuotaList({ ...this.page, ...this.params }).then((res) => {
        if (res.success) {
          this.tableData = res.data.records
          this.page.total = res.data.total
        }
      })
    },
    removeChildrenAtLevel(tree, targetLevel) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的level是否为目标level
        if (tree[i].level === targetLevel) {
          // 如果是的话，移除children属性
          delete tree[i].children
        }

        // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
        if (tree[i].children && tree[i].children.length > 0) {
          this.removeChildrenAtLevel(tree[i].children, targetLevel)
        }
      }

      return tree
    },
  },
  watch: {
    page(newVal, oldVal) {
      if (
        !(
          newVal.pageIndex === oldVal.pageIndex &&
          newVal.pageSize === oldVal.pageSize
        )
      ) {
        this.getList()
      }
    },
    params: {
      handler: function () {
        {
          if (this.page.pageIndex === 1) {
            this.getList()
          } else {
            this.page.pageIndex = 1
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.publish-content {
  width: 100%;
  height: 100%;
  padding: 20px;
  border-radius: 10px;
  box-sizing: border-box;
  .head {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
  }
  .search {
    .el-cascader {
      margin-right: 10px;
    }
    .el-select {
      margin-right: 10px;
      width: 120px;
    }
    .el-input {
      width: 230px;
    }
  }
  .progress-bg {
    height: 10px;
    border: 1px solid #02bcca;
    border-radius: 5px;
    .progress {
      height: 100%;
      background: #02bcca;
      border-radius: 5px;
    }
  }
}
</style>
